import copy
import os.path

import openpyxl
path = os.path.dirname(__file__).split("core")[0]

def get_all_files(file_path):
    files = os.listdir(file_path)
    file_paths = []
    for file in files:
        if file.startswith("test") and (file.endswith(".xlsx") or file.endswith(".xls")):
          file_paths.append(os.path.join(path,file_path,file))
    return file_paths

def parse_test_case(file_path):
    workbook = openpyxl.load_workbook(file_path)
    sheets = workbook.worksheets
    cases = []
    for sheet in sheets:
        current_case = {}
        steps = []
        for row in sheet.iter_rows(min_row=2, values_only=True):
            if row[0] is not None and row[3] == "feature_name":
                if current_case:
                    current_case["steps"] = steps
                    cases.append(copy.deepcopy(current_case))
                    current_case = {}
                    steps = []
                current_case["feature_name"] = row[4]
            elif row[0] is not None and row[3] == "browser":
                current_case["browser"] = row[4]
            elif row[1] is not None and row[3] == "case_name":
                if steps:
                    current_case["steps"] = steps
                    cases.append(copy.deepcopy(current_case))
                    steps = []
                current_case["case_name"] = row[4]
            else:
                step = {
                    "step_name": row[2],
                    "keyword": row[3],
                    "args": [_ for _ in row[4:] if _]
                }
                steps.append(step)
        if steps:
            current_case["steps"] = steps
            cases.append(copy.deepcopy(current_case))
    return cases

def read_excel(file_path):
    all_cases = []
    file_paths = get_all_files(file_path)
    for file in file_paths:
        cases = parse_test_case(file)
        all_cases.extend(cases)
    return all_cases




